<template>
  <div class="groupview" id="groupView">
    <div class="titleView">{{ plotInfo?.name }}</div>
    <div v-if="false" class="plotInfo" :style="transformStyle">
      <div class="infoHeader">
        <span class="title">地块详情</span>
        <el-icon :size="20" @click="switchInfo" style="cursor: pointer">
          <ArrowUp v-show="showInfo" />
          <ArrowDown v-show="!showInfo" />
        </el-icon>
      </div>
      <div v-show="showInfo" class="infoContent">
        <div class="map">
          <el-image style="width: 100%; height: 100%" :src="plotInfo?.imageUrl" fit="cover"></el-image>
        </div>
        <div class="common">
          <div class="label">区</div>
          <div class="desc">
            <dict-tag :options="sys_hn_areacode" :value="plotInfo?.areaCode" />
          </div>
        </div>
        <div class="common">
          <div class="label">项目名称</div>
          <div class="desc">{{ plotInfo?.name }}</div>
        </div>
        <div class="common">
          <div class="label">位置</div>
          <div class="desc">{{ plotInfo?.location }}</div>
        </div>
        <div class="common">
          <div class="label">规划用途</div>
          <div class="desc">{{ plotInfo?.ghyt }}</div>
        </div>
        <div class="common">
          <div class="label">建设用途面积</div>
          <div class="desc">{{ plotInfo?.jzydmj || 0 }}公顷</div>
        </div>
        <div class="common">
          <div class="label">规划建筑规模</div>
          <div class="desc">{{ plotInfo?.jzydgm || 0 }}平方米</div>
        </div>
      </div>
    </div>
    <!-- 全景列表区域 -->
    <div class="swiperBox">
      <div class="leftHidden" @click="switchSwiper">
        <img v-if="showSwiper" src="../../assets/images/right.png" alt="right">
        <img v-else src="../../assets/images/left.png" alt="left">
      </div>
      <swiper :slides-per-view="4" :space-between="0">
        <template v-for="(item, index) in fullList" :key="item.id">
          <swiper-slide>
            <div class="item" @click="switchImage(item, index)" :class="[index === currentIndex ? 'active' : '']">
              <div class="title">{{ item.name }}</div>
              <el-image lazy :src="item.url" fit="cover" />
            </div>
          </swiper-slide>
        </template>
      </swiper>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/css";
import { ref, watch } from "vue";
import { getGatherDetails } from "@/api/gather";
import { get720List } from "@/api/720.js";
import { useRouter } from "vue-router";
import { Viewer } from "@photo-sphere-viewer/core";
import { MarkersPlugin } from "@photo-sphere-viewer/markers-plugin";
import { EquirectangularTilesAdapter } from "@photo-sphere-viewer/equirectangular-tiles-adapter";
import { CubemapTilesAdapter } from "@photo-sphere-viewer/cubemap-tiles-adapter";
import "@photo-sphere-viewer/core/index.css";
import "@photo-sphere-viewer/markers-plugin/index.css";
import { pictPreview } from "../../api/720.js";
const { proxy } = getCurrentInstance();
const { sys_hn_areacode } = proxy.useDict("sys_hn_areacode");
const router = useRouter();
let showInfo = ref(true);
let showSwiper = ref(true);
let swiperRight = ref('10px');
let viewer = ref(null);
let panoramaObj = ref(null);
let pictType = ref(null);
let markersPlugin = ref(null);
let markers = ref([]);
let url = ref("");
let plotInfo = ref(null);
let infoHeight = ref("600px");
let fullList = ref([]);
let allData = ref(null);
let currentIndex = ref(0);
watch(allData, (newVal) => {
  init();
});

async function getInfo() {
  const { data } = await getGatherDetails(
    router.currentRoute.value.query.groupId
  );
  plotInfo.value = data;
  if (data?.extraProperties) {
    let result = JSON.parse(data.extraProperties);
    plotInfo.value.jzydmj = result.find(
      (item) => item.dictValue === "jzydmj"
    )?.value;
    plotInfo.value.ghyt = result.find(
      (item) => item.dictValue === "ghyt"
    )?.value;
    plotInfo.value.jzydgm = result.find(
      (item) => item.dictValue === "jzydgm"
    )?.value;
  }
  plotInfo.value.imageUrl =
    import.meta.env.VITE_APP_PIC_BASE_API + data?.thumb?.path;
}
function switchInfo() {
  showInfo.value = !showInfo.value;
  if (showInfo.value) {
    infoHeight.value = "600px";
  } else {
    infoHeight.value = "60px";
  }
}

// 获取全景列表
async function getList() {
  const { rows } = await get720List({
    groupId: router.currentRoute.value.query.groupId,
  });
  fullList.value = rows.map((item) => {
    return {
      ...item,
      url: import.meta.env.VITE_APP_PIC_BASE_API + item.thumb.path,
    };
  });
  getData(rows[0]?.id);
}

async function getData(id) {
  if (!id) return;
  try {
    const { data } = await pictPreview(id);
    allData.value = data;

    if (allData.value) {
      allData.value.pictureType === "0"
        ? (pictType.value = EquirectangularTilesAdapter)
        : (pictType.value = CubemapTilesAdapter);
      url.value =
        import.meta.env.VITE_APP_PIC_BASE_API + allData.value.thumb.path;
    }
    if (allData.value?.annotation) {
      markers.value = JSON.parse(allData.value.annotation);
    } else {
      markers.value = [];
    }
    changeType();
  } catch (error) {
    allData.value = null;
  }
}

// 切换全景照片
function switchImage(row, index) {
  currentIndex.value = index;
  getData(row.id);
  markersPlugin.value.clearMarkers();
  viewer.value.destroy();
}

function switchSwiper() {
  showSwiper.value = !showSwiper.value;
  let left = document.querySelector('.swiperBox').offsetWidth - 10
  showSwiper.value ? (swiperRight.value = "10px") : (swiperRight.value = `-${left}px`);
}
function changeType() {
  // 平面
  if (allData.value?.pictureType === "0") {
    panoramaObj.value = {
      width: allData.value.tilesValue.width,
      cols: allData.value.tilesValue.cols,
      rows: allData.value.tilesValue.rows,
      baseUrl: url.value,
      tileUrl: (col, row) => {
        const tileIdentifier = `${row}_${col}`;
        const item = allData.value.tilesValue.files[tileIdentifier];
        return (
          import.meta.env.VITE_APP_PIC_BASE_API +
          "/" +
          allData.value.tilesValue.folder +
          "/" +
          item
        );
      },
    };
  } else if (res.data?.pictureType === "1") {
    // 立体
    Object.keys(allData.value.cubeValue).forEach((key) => {
      allData.value.cubeValue[key] =
        import.meta.env.VITE_APP_PIC_BASE_API + allData.value.cubeValue[key];
    });
    panoramaObj.value = {
      faceSize: allData.value.cubeTilesValue.file[0].width,
      nbTiles: 8,
      baseUrl: allData.value.cubeValue,
      tileUrl: (face, col, row) => {
        let key = allData.value.cubeValue[face].split("/").at(-1).split(".")[0]; // 文件名称
        let target = allData.value.cubeTilesValue.file.find(
          (item) => item.folder.indexOf(key) > -1
        );
        const tileIdentifier = `${row}_${col}`;
        const item = target.files[tileIdentifier];
        return (
          import.meta.env.VITE_APP_PIC_BASE_API +
          "/" +
          target.folder +
          "/" +
          item
        );
      },
    };
  }
}

function init() {
  const config = {
    container: "groupView",
    adapter: pictType.value,
    panorama: panoramaObj.value,
    touchmoveTwoFingers: false,
    size: {
      height: "100%",
      width: "100%",
    },
    moveSpeed: 2,
    zoomSpeed: 10,
    navbar: [
      // 底部导航栏，依次是自动播放、缩放、图库、文字、全屏
      "zoom",
      "move",
      "download",
      "description",
      "caption",
      "fullscreen",
    ],
    plugins: [
      [
        MarkersPlugin,
        {
          markers: [],
        },
      ],
    ],
  };
  viewer.value = new Viewer(config);

  // 全景图加载完成时的回调。获取标注数据
  viewer.value.addEventListener("ready", () => {
    initMarkers();
    btnConfig();
  });
  markersPlugin.value = viewer.value.getPlugin(MarkersPlugin); // 获取标注插件

  markersPlugin.value.addEventListener("select-marker", ({ marker }) => {
    if (marker.config.type === "全景") {
      fullGo(marker);
    }
  });
}

// 初始化标注
function initMarkers() {
  if (!markers.value.length) return;
  markers.value.forEach((item) => {
    markersPlugin.value.addMarker(item.config);
  });
}

function btnConfig() {
  viewer.value.setOption("fisheye", allData.value.detailsValue.enableFisheye);
  viewer.value.setOption(
    "mousewheelCtrlKey",
    allData.value.detailsValue?.enableCtrlZoom
  );
  viewer.value.setOption(
    "mousemove",
    allData.value.detailsValue?.enableMouseInteraction
  );
  viewer.value.setOption("minFov", allData.value.detailsValue?.minViewAngle);
  viewer.value.setOption("maxFov", allData.value.detailsValue?.maxViewAngle);
  viewer.value.setOption(
    "mousewheel",
    allData.value.detailsValue?.enableMouseWheel
  );
  viewer.value.setOption("caption", allData.value.name);
  viewer.value.setOption("description", allData.value.remark);

  viewer.value.rotate({
    yaw: allData.value.detailsValue?.defaultVerticalAngle || 0,
    pitch: allData.value.detailsValue?.defaultHorizontalAngle || 0,
  });
  viewer.value.setOption("sphereCorrection", {
    pan: allData.value.detailsValue?.correctPan,
    tilt: allData.value.detailsValue.correctTilt,
    roll: allData.value.detailsValue?.correctRoll,
  });
  viewer.value.zoom(allData.value.detailsValue?.fullscreenButton);
  allData.value.detailsValue.name = allData.value.name;
  allData.value.detailsValue.remark = allData.value.remark;
  let target = {
    moveButton: "move",
    zoomButton: "zoom",
    downloadButton: "download",
    remark: "description",
    name: "caption",
    fullscreenButton: "fullscreen",
  };
  let arr = [];
  for (const key in target) {
    if (allData.value.detailsValue[key]) {
      arr.push(target[key]);
      viewer.value.setOption("navbar", arr); // 动态隐藏导航栏工具
    } else if (!arr.length) {
      viewer.value.setOption("navbar", []); // 动态隐藏导航栏工具
    }
  }
}

async function fullGo(marker) {
  await getData(marker.config.link);
  if (!allData.value) return ElMessage.error("跳转全景照片不存在！");
  markersPlugin.value.clearMarkers();
  viewer.value.destroy();
}

onMounted(async () => {
  await getInfo();
  await getList();
});
</script>
<style lang="scss" scoped>
.groupview {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;

  .titleView {
    position: absolute;
    left: 10px;
    top: 15px;
    font-size: 20px;
    color: white;
    z-index: 99;
  }

  .plotInfo {
    z-index: 99;
    color: #ffffffde;
    width: 320px;
    height: v-bind(infoHeight);
    background: rgba(52, 52, 52, 0.4);
    position: absolute;
    left: 10px;
    top: 50px;
    padding: 10px;
    border-radius: 5px;
    display: flex;
    flex-direction: column;

    .infoHeader {
      height: 40px;
      line-height: 40px;
      font-size: 18px;
      font-weight: bold;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }

    .infoContent {
      flex: 1;

      .map {
        width: 100%;
        height: 210px;

        >img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }
    }
  }

  .swiperBox {
    z-index: 99;
    position: absolute;
    right: v-bind(swiperRight);
    bottom: 50px;
    width: 920px;
    height: 180px;
    display: flex;
    justify-content: space-between;
    transition: all 0.3s ease-out;
  }

  ::v-deep .swiper {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;

    .el-carousel__container {
      width: 250px;
    }

    .item {
      height: 100%;
      width: 220px;
      border-radius: 5px;
      overflow: hidden;
      margin-right: 20px;
      border: 2px solid transparent;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      padding: 10px;
      background-color: #0006;
      cursor: pointer;

      .title {
        text-align: center;
        color: white;
        font-size: 14px;
      }
    }
  }
}

.common {
  width: 100%;
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid white;
  color: #c5c5c5;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .label {
    font-weight: bold;
  }

  .desc {
    color: white;
  }
}

::v-deep .psv-tooltip {
  max-width: 1000px !important;
}

::v-deep .psv-fullscreen-button {
  position: absolute;
  right: 10px;
}

::v-deep .marker-tooltip-container {
  width: 300px;
  position: relative;
  overflow: hidden;

  .marker-title {
    font-size: 18px;
    font-weight: bold;
    white-space: break-word;
  }

  .marker-description {
    word-wrap: break-word;
  }

  .scroll-container {
    height: 150px;
    width: 100%;
    display: flex;
    overflow-x: auto;
    overflow-y: hidden;

    .tooltipImage {
      width: 300px;
      height: 150px;
      object-fit: cover;
    }
  }
}

::v-deep .psv-loader-text {
  color: black;
}

.active {
  border: 2px solid hsl(236, 78%, 56%) !important;
}

.leftHidden {
  width: 12px;
  height: 180px;
  line-height: 180px;
  text-align: center;
  z-index: 999;
  cursor: pointer;
  background-color: rgba(0, 0, 0, .5);
  border-top-left-radius: 4px;
  border-bottom-left-radius: 4px;
  transition: all 0.3s ease-out;

  >img {
    width: 12px;
    height: 32px
  }
}

::v-deep .el-image {
  width: 200px;
  height: 200px;
}
</style>
